var CryptoJS = require("@/utils/CryptoJS.js");
import store from '@/store/index.js'
let baseMmac=''
let serviceId='6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
let characteristicId="6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
let writeCharacteristicId="6E400002-B5A3-F393-E0A9-E50E24DCCA9E"

let Fn=''

		export const bluetooth = function (mac,fn,isStop) {
				baseMmac=mac
				if(fn){
					Fn=fn
				}
				
				console.log("初始化蓝牙开始,微信版")
				uni.openBluetoothAdapter({
					success: (e) => {
						uni.showToast({
							icon: "none",
							title: "初始化蓝牙成功！",
							duration: 3000
						})
						console.log('初始化蓝牙成功:' + e.errMsg);
						// 初始化完毕开始搜索
						startBluetoothDeviceDiscovery()
					},
					fail: res => {
						const systemSetting = uni.getSystemSetting()
						console.log(systemSetting.bluetoothEnabled)
						console.log("请打开手机蓝牙！")
						// uni.showToast({
						// 	icon: "none",
						// 	title: "请打开手机蓝牙！",
						// 	duration: 3000
						// })
						uni.showModal({
							title: '提示',
							content: '获取蓝牙授权失败，是否授权打开蓝牙',
							success: (res) => {
								if (res.confirm) {
									uni.openSetting({
										success(res) {
											console.log(res)
											console.log(res.authSetting['scope.bluetooth'])
											if (!res.authSetting['scope.bluetooth']) {
											      uni.authorize({
											        scope: 'scope.bluetooth',
											        success:(res) => {
											          // 用户已经同意小程序使用蓝牙功能，后续 接口不会弹窗询问
											         console.log(res)
											        }
											    })
											}
										}
									})
								}
							},
						})	
					}
				});
			}
			
function startBluetoothDeviceDiscovery() {
				console.log("开始查找设备",baseMmac)
				//在页面显示的时候判断是都已经初始化完成蓝牙适配器若成功，则开始查找设备
				uni.startBluetoothDevicesDiscovery({
					//services: ['2007240088'],
					allowDuplicatesKey: false,
					success: res => {
						console.log(res)
						//this.onBluetoothDeviceFound();
						// setTimeout(this.getBluetoothDevices,500)
						onBluetoothDeviceFound();
					},
					fail: res => {
						console.log("查找设备失败",res)
						console.log("查找设备失败",baseMmac)
						uni.showToast({
							icon: "none",
							title: "查找设备失败！",
							duration: 3000
						})
					}
				});
			}

function onBluetoothDeviceFound() {
				console.log("监听寻找新设备");
				wx.offBluetoothDeviceFound()
				uni.onBluetoothDeviceFound(res => {
					console.log('开始监听寻找到新设备的事件',baseMmac);
					console.log(res)
					if (res.devices[0].advertisData != null) { //判断对象是否为null，advertisData不一定有，解决Android、IOS获取mac问题
						//重点 根据advertisData 取出mac进行拼接
						let des = res.devices[0];
						let bf = res.devices[0].advertisData;
						let mac = Array.prototype.map.call(new Uint8Array(bf), x => ('00' + x.toString(16)).slice(-2)).join(':');
						
						//判断mac是否为服务器传入mac
						// console.log('mac')
						// console.log(mac.toUpperCase())
						// console.log(des.deviceId)
						// console.log(des.name)
						console.log('namenamenamenamenamename',des.localName)
						// console.log('mac')
						// if (baseMmac == mac.toUpperCase()&&res.devices[0].advertisServiceUUIDs) {
						if (baseMmac == des.localName || baseMmac == des.name) {
							console.log(des)
							console.log('找到设备')
							uni.stopBluetoothDevicesDiscovery();

							// console.log(characteristicId,des.advertisServiceUUIDs[0])
							createBLEConnection(des.deviceId);
							console.log(des.localName)
							uni.setStorageSync("mid",des.localName)
							
						}
					}
					
				});
			}
function createBLEConnection(deviceId) {
				// uni.setStorageSync('deviceId',deviceId)
				console.log('开始连接蓝牙设备')
				uni.showToast({
					icon: "none",
					title: "蓝牙连接中",
					duration: 3000
				})
				uni.createBLEConnection({
					deviceId: deviceId,
					success: res => {
						console.log(res)
						uni.setStorageSync('deviceId',deviceId)
						getBLEDeviceServices(deviceId);
					},
					fail: res => {
						console.log('蓝牙连接失败',res)
						uni.closeBluetoothAdapter()
					}
				})
			}
			
function getBLEDeviceServices(deviceId) {
					uni.getBLEDeviceServices({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: deviceId,
						success: (res) => {
							console.log(res)
							console.log('----------------------测试断开2------------------')
							for (let i = 0; i < res.services.length; i++) {
								if (res.services[i].isPrimary) {
									if (deviceId) {
										serviceId=res.services[0].uuid
										getBLEDeviceCharacteristics(deviceId);
										break; 
									}
								}
							}
						}
					})				
			}
function getBLEDeviceCharacteristics(deviceId) {
				console.log("进入特征：baseMmac："+baseMmac);
				console.log(deviceId,serviceId)
				setTimeout(() => {
					uni.getBLEDeviceCharacteristics({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: deviceId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId: serviceId,
						success: (res) => {
							if(baseMmac.indexOf('23THCBCL') == -1&&baseMmac.indexOf('CD') == -1){
								characteristicId=res.characteristics[0].uuid.toUpperCase()
								writeCharacteristicId=res.characteristics[1].uuid.toUpperCase()
										notifyBLECharacteristicValueChange(deviceId);
							}else{
								characteristicId=res.characteristics[1].uuid.toUpperCase()
								writeCharacteristicId=res.characteristics[0].uuid.toUpperCase()
										notifyBLECharacteristicValueChangeforCD(deviceId);
							}
							
						},
						fail: (res) => {
							console.log(res)
						}
					})
				}, 0)
			}
function notifyBLECharacteristicValueChangeforCD(deviceId){
				console.log("启用 notify 功能 notifyBLECharacteristicValueChangeforCD");
				console.log(deviceId,serviceId,characteristicId);
				uni.setBLEMTU({
				      deviceId: deviceId,
				      mtu:88,
				      success:(res)=>{
				        console.log("setBLEMTU success>>", res)
				      },
				      fail:(res)=>{
				        console.log("setBLEMTU fail>>", res)
				      },
					  complete:(res)=>{
							uni.notifyBLECharacteristicValueChange({
							  state: true, // 启用 notify 功能
							  deviceId: deviceId,
							  serviceId: serviceId,
							  characteristicId: characteristicId,
							  success: function (res) {
								  uni.showToast({
									icon: "none",
									title: "连接成功！",
									duration: 3000
								  })
								store.commit('user/UPDATE_STATUS', true);
								  // that.verifyOpenId();
								uni.setStorageSync('deviceId',deviceId)
								
							
								
								let mVal = uni.getStorageSync('MING_KEY');
								sentOrder9('ae01' + mVal);
								onBLECharacteristicValueChange();   //监听特征值变化
							  },
							  fail: function (res) {
								  console.log('fail----------------------')
								  console.log(res)
								uni.showToast({
								  title: 'notify启动失败',
								  mask: true
								});
								setTimeout(function () {
								  uni.hideToast();
								}, 2000)
							  }
							})
				      },
				    })
			
			  }
function notifyBLECharacteristicValueChange(deviceId){
				console.log("启用 notify 功能");
				console.log(deviceId,serviceId,characteristicId);
				uni.setBLEMTU({
				      deviceId: deviceId,
				      mtu:88,
				      success:(res)=>{
				        console.log("setBLEMTU success>>", res)
				      },
				      fail:(res)=>{
				        console.log("setBLEMTU fail>>", res)
				      },
					  complete:(res)=>{
							uni.notifyBLECharacteristicValueChange({
							  state: true, // 启用 notify 功能
							  deviceId: deviceId,
							  serviceId: serviceId,
							  characteristicId: characteristicId,
							  success: function (res) {
								  uni.showToast({
									icon: "none",
									title: "连接成功！",
									duration: 3000
								  })
								store.commit('user/UPDATE_STATUS', true);
								  // that.verifyOpenId();
								uni.setStorageSync('deviceId',deviceId)
								
							
								
								let mVal = uni.getStorageSync('MING_KEY');
								
								sentOrder9('ae01' + mVal);
								//连接成功后直接握手
								//先做异或处理
								console.log("启用 notify 功能:打印握手后的指令：");
								let a = 0;
								let content = "FF55120101" + baseMmac + "016C6F67696E"
								for (let i = 0; i < content.length / 2; i++) {
								    a = a ^ parseInt(content.substring(i * 2, (i * 2) + 2), 16);
								}
								let result = a.toString(16);
								if (result.length == 1) {
								    result= "0" + result;
								} else {
								    result= result;
								}
								
								let orderStr2 = (content+result).toUpperCase();
								console.log('')
								console.log(orderStr2)
								let typedArray = new Uint8Array(orderStr2.match(/[\da-f]{2}/gi).map(function (h) {
								  return parseInt(h, 16)
								}))
								let buffer1 = typedArray.buffer
								orderStr2 = buffer1
								writeBLECharacteristicValue(orderStr2);
								onBLECharacteristicValueChange();   //监听特征值变化
							  },
							  fail: function (res) {
								  console.log('fail----------------------')
								  console.log(res)
								uni.showToast({
								  title: 'notify启动失败',
								  mask: true
								});
								setTimeout(function () {
								  uni.hideToast();
								}, 2000)
							  }
							})
				      },
				    })
			
			  }
function sentOrder9(val) {
				console.log("连接蓝牙 验证aes");
			    let orderStr = val;
			    var result = "";
			    for (let i = 0; i < orderStr.length; i++) {
			      if (i % 2 == 0) {
			        result += '0x';
			      }
			      result += orderStr[i];
			    }
			    let orderStr2 = result.toUpperCase();
			    console.log('')
			    console.log(orderStr2)
			    let typedArray = new Uint8Array(orderStr2.match(/[\da-f]{2}/gi).map(function (h) {
			      return parseInt(h, 16)
			    }))
			    let buffer1 = typedArray.buffer
			    orderStr2 = buffer1
			    writeBLECharacteristicValue(orderStr2);
			  }
export function writeBLECharacteristicValue(order) { 
			     console.log('发送二进制数据')
			     console.log(order)
			    var that = this;
			    let byteLength = order.byteLength;
				console.log(byteLength)
			    uni.onBluetoothAdapterStateChange(function (res) {
			      console.log('onBluetoothAdapterStateChange', res)
				})
				uni.writeBLECharacteristicValue({
				  deviceId: uni.getStorageSync('deviceId'),
				  serviceId: serviceId,
				  characteristicId: writeCharacteristicId,
				  // 这里的value是ArrayBuffer类型
				  value: order,
				  
				  //wangk 2020-12-06 update
				  success: function (res) {
					  // that.readBLECharacteristicValue()
					  console.log(res)
					  console.log('开始跳转')
					  
					  nums = nums +1
					  console.log(nums)
					  if(nums<5){
						  
						  // sentOrder24(1)
						  
						 //  let results = '0XAA0X0216070025230X01'
						 //  let orderStr2 = results.toUpperCase();
						 //  console.log('')
						 //  console.log(orderStr2)
						 //  let typedArray = new Uint8Array(orderStr2.match(/[\da-f]{2}/gi).map(function (h) {
						 //    return parseInt(h, 16)
						 //  }))
						 //  let buffer1 = typedArray.buffer
						 //  orderStr2 = buffer1
						  
						  
					  // writeBLECharacteristicValue(orderStr2);
					  }
					  
					  // write
					  // 0XAA0X0217810339130X2
					  // 
					  
					  console.log('=====')
					  
				  },
				  fail: function (res) {
				     console.log(res)
					 console.log('跳转失败')
				  }
				})
			  }
			  
			  
			  function sentOrder24(slot) {
			  	var that = this;
			  	let ksMid = getOrderStr('1607002523');
				console.log('orderStr1')
				console.log(ksMid)
				
			  	let a = Number(slot).toString(16).toUpperCase()
			  	let slotStr = a.length==1?('0x0'+a):('0x'+a)
			  	
			  	var orderStr = '0XAA0X02' + ksMid + slotStr; //指令
				console.log('orderStr')
				console.log(orderStr)
			  	let typedArray = new Uint8Array(orderStr.match(/[\da-f]{2}/gi).map(function(h) {
			  		return parseInt(h, 16)
			  	}))
			  	let buffer1 = typedArray.buffer
			  	orderStr = buffer1
			  	writeBLECharacteristicValue(orderStr);
			  	
			  }
			  function getOrderStr(mid) {
			      let strDl = mid;
			      let getOrderStrs = '';
			      for (var i = 0, len = strDl.length; i < len; i++) {
			        getOrderStrs += '0x0' + strDl[i];
			      }
			      return getOrderStrs;
			    }
			  
			  var nums = 1;
			 function string2buffer(str) {
			      // 首先将字符串转为16进制
			      let val = ""
			      for (let i = 0; i < str.length; i++) {
			        if (val === '') {
			          val = str.charCodeAt(i).toString(16)
			        } else {
			          val += ',' + str.charCodeAt(i).toString(16)
			        }
			      }
			      // 将16进制转化为ArrayBuffer
			      return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
			        return parseInt(h, 16)
			      })).buffer
			    }
			  
			  
function onBLECharacteristicValueChange() {
				console.log('监听低功耗蓝牙设备的特征值变化')
			    uni.onBluetoothAdapterStateChange(function (res) {
			      // console.log('onBluetoothAdapterStateChange', res)
			    })
				wx.offBLECharacteristicValueChange()
			    uni.onBLECharacteristicValueChange(function (res) {
					console.log('蓝牙返回的数据',res)
			      let strs = buf2hex(res.value);
				  
				   console.log(strs)
			      // let newStr = '';
			       console.log(strs.substring(0, 4))
			
			      if (strs.substring(0, 4) === 'bb02') {
			        // newStr = '指定锁：' + strs;
			      } else if (strs.substring(0, 4) === 'bb03') {
			        // newStr = '缺货锁：' + strs;
			      } else if (strs.substring(0, 4) === 'bb04') {
			        // newStr = '全部锁：' + strs;
			      } else if (strs.substring(0, 4) === 'bb05') {
			        console.log(strs.substring(strs.length - 2))
			        
			      } else if (strs.substring(0, 4) === 'bb06') {
			        // let strs2 = strs.substring(strs.length - 2);
			        // newStr = '电量：' + strs2.slice(0, 1) + '.' + strs2.slice(1) + 'v';					
			        // let dl = strs2.slice(0, 1) + '.' + strs2.slice(1);
			        // that.newStr=newStr	
									
									
					let strs2 = strs.substring(strs.length - 2);
					// newStr = '电量：' + strs2.slice(0, 1) + '.' + strs2.slice(1) + 'v';
					
					let dl = strs2.slice(0, 1) + '.' + strs2.slice(1);
					//that.levelName=strs2.slice(0, 1) + '.' + strs2.slice(1) //原有
					//wangk update
					//大于4V显示100%图标显示绿色
					//3.7-4V之间80%图标显示绿色
					//3.5-3.7之间60%图标显示黄色
					//小于3.5显示25%图标显示红色
					
					//debugger;
					let levelName
					if(dl>4){
						levelName = '/static/imgs/dianliang100.png';
					} else if(dl>3.7 && dl <=4){
						levelName = '/static/imgs/dianliang80.png';
					} else if(dl>3.5 && dl <=3.7){
						levelName = '/static/imgs/dianliang50.png';
					} else if(dl>3.0&&dl<3.5){
						levelName = '/static/imgs/dianliang20.png';
					}else if(dl<3.0){
						levelName = '/static/imgs/dianliang0.png';
					}
					
					uni.setStorageSync('levelName',levelName)
					
					console.log('电量：' + strs2.slice(0, 1) + '.' + strs2.slice(1) + 'v')					
					console.log('电量：' + strs2.slice(0, 1) + '.' + strs2.slice(1) + 'v')
					console.log('-------------------------wk--home');
									
									
			      } else if (strs.substring(0, 4) === 'ae02') {
			        //解密
			        let valStr1 = strs.substring(4, strs.length);
			        let valStr2 = CryptoJS.transTwoArry(valStr1.toUpperCase());
			        let decryptVal = CryptoJS.decrypt(valStr2).replace(/\s+/g, "");
			        let decryptVal2 = CryptoJS.transTwoArry(decryptVal.substring(0, decryptVal.length / 2));
			
			        let toLowerCaseStr = decryptVal2.replace(/\s+/g, "").toLowerCase();
			        let strogKey = uni.getStorageSync('MING_KEY');
			        if (toLowerCaseStr == strogKey) {
			          // newStr = '解密成功！' + decryptVal2;
					  console.log('解密成功！' + decryptVal2)
					  if(Fn){
						  Fn()
					  }
			        } else {
			          // newStr = '解密失败！';
					  console.log('解密失败！')
			          // uni.closeBluetoothAdapter()
			        }
			        // that.newStr=newStr
			      } else if (strs.substring(0, 4) === 'ae03') {
			        // if (that.isDecrypt) {
			          let valDecrypt1 = strs.substring(4, strs.length);
			          let valDecrypt2 = valDecrypt1.toUpperCase();
			          let val = CryptoJS.transTwoArry(valDecrypt2);
			          // console.log(val)
			          let encryptVal = CryptoJS.encrypt(val).replace(/\s+/g, "");
			          let encryptVal2 = CryptoJS.transTwoArry(encryptVal.substring(0, encryptVal.length / 2));
			          // newStr = '加密：' + encryptVal2 + "\n"
			          //that.newStr=newStr
			          let encryptVal3 = encryptVal2.replace(/\s+/g, "");
					  // that.isDecrypt=false;
			          sentOrder9('ae04' + encryptVal3);
			        // } else {
			        //   return;
			        // }
			      }
			    });
			  }
function buf2hex(buffer) { // buffer is an ArrayBuffer
			    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
			  }
			  
export const write = writeBLECharacteristicValue